package com.grt.condify.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.grt.condify.dto.PersonListDTO;
import com.grt.condify.entity.Person;
import com.grt.condify.exception.CondifyException;
import com.grt.condify.parser.MybatisSearchParser;
import com.grt.condify.service.PersonService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Api(tags = "person")
@RestController
@RequestMapping("/person")
public class PersonController {

    public static Logger logger = LoggerFactory.getLogger("PersonController");

    @Autowired
    PersonService personService;


    @PostMapping("/addPerson")
    @ApiOperation("添加用户")
    public JSONObject addPerson(Person person) {
        JSONObject result = new JSONObject();
        personService.saveOrUpdate(person);
        result.put("code", 200);
        return result;
    }

    @PostMapping("/editPerson")
    @ApiOperation("编辑用户")
    public JSONObject editPerson(Person person) {
        JSONObject result = new JSONObject();

        personService.saveOrUpdate(person);

        result.put("code", 200);
        return result;
    }

    @GetMapping("/queryPersons")
    @ApiOperation("查询用户列表")
    public List<Person> queryPersons(PersonListDTO personListDTO) throws CondifyException {

        QueryWrapper queryWrapper = MybatisSearchParser.buildQueryWrapper(personListDTO);
        return personService.list(queryWrapper);
    }

    @GetMapping("/queryPersonByPage")
    @ApiOperation("查询用户列表带分页")
    public IPage<Person> queryPersonByPage(PersonListDTO personListDTO) throws CondifyException {
        IPage<Person> page = MybatisSearchParser.buildPage(personListDTO);

        QueryWrapper queryWrapper = MybatisSearchParser.buildQueryWrapper(personListDTO);
        page = personService.queryForPage(page,queryWrapper);
        return page;
    }

    @GetMapping("/delPerson")
    @ApiOperation("删除用户")
    public JSONObject delPerson(Integer personId) {
        JSONObject result = new JSONObject();

        personService.removeById(personId);

        result.put("code", 200);
        return result;
    }

    @GetMapping("/getPerson")
    @ApiOperation("根据用户id获取用户详情")
    public JSONObject getPerson(Integer personId) {
        JSONObject result = new JSONObject();

        Person person = personService.getById(personId);

        result.put("code", 200);
        result.put("data", person);
        return result;
    }

}
